package com.example.finaltool.utils;

import com.example.finaltool.model.MyRuntimeException;
import com.example.finaltool.model.config.Data;
import com.example.finaltool.model.DepInfo;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.util.CollectionUtils;

import java.io.*;
import java.util.List;
import java.util.Locale;
import java.util.Map;

@Slf4j
public class FileUtils {

    private FileUtils() {
    }

    private static void saveToText(File file, String content) throws IOException {
        if (!file.exists() && !file.createNewFile()) {
            throw new MyRuntimeException("无法创建文件: " + file.getAbsolutePath());
        }
        try (Writer writer = new FileWriter(file, true)) {
            writer.write(System.lineSeparator() + content);
        }
    }

    public static void saveCoreToText(File file, Map<String, String> core, DepInfo info) throws IOException {
        StringBuilder builder = new StringBuilder();
        core.keySet().forEach(k -> builder.append("// ").append(k).append(": ").append(core.get(k)).append(System.lineSeparator()));
        if (info != null) {
            builder.append("// 服务支撑人员: ").append(info.getFuwu()).append(System.lineSeparator());
            builder.append("// 乡镇管理人员: ").append(info.getXiangzhen()).append(System.lineSeparator());
            info.getCunDepInfoList().forEach(c -> builder.append("// ").append(c.getCunName()).append(": ").append(c.getCunDepId()).append(", 农户: ").append(c.getNonghu()).append(", 服务支撑人员: ").append(c.getFuwu()).append(System.lineSeparator()));
        }
        saveToText(file, builder.toString());
    }

    public static void saveNotFoundArea(List<String> areaNames, File txt) throws IOException {
        if (CollectionUtils.isEmpty(areaNames))
            return;
        if (!txt.exists())
            throw new MyRuntimeException("未找到文件: " + txt.getAbsolutePath());
        File saved = new File(txt.getParentFile().getAbsolutePath() + File.separator + "未匹配行政区划.txt");
        if (!saved.exists()) {
            try {
                if (!saved.createNewFile())
                    throw new MyRuntimeException("无法创建文件: " + saved.getAbsolutePath());
            } catch (IOException e) {
                throw new MyRuntimeException("创建文件异常: " + saved.getAbsolutePath() + " " + e.getMessage());
            }
        }
        StringBuilder builder = new StringBuilder(System.lineSeparator());
        builder.append("未匹配的行政区划名称（若上级未匹配，则下级均未匹配）").append(System.lineSeparator());
        areaNames.forEach(a -> builder.append(a).append(System.lineSeparator()));
        saveToText(saved, builder.toString());
        log.info("已导出未匹配的行政区划至" + saved.getAbsolutePath());
    }

    public static boolean isText(File file) {
        return file.getName().toLowerCase(Locale.ROOT).endsWith(".txt");
    }

    public static File fillData(String filePath, Data data) throws IOException {
        filePath = filePath.replace(" ", "");
        File dataFile = new File(filePath);
        if (!dataFile.exists()) {
            throw new MyRuntimeException("未找到文件：\"" + filePath + "\"");
        }
        FileUtils.read(data, dataFile);
        log.info("读取到的信息：");
        PrintUtils.showData(data);
        return dataFile;
    }

    public static void read(Data data, File file) throws IOException {
        try (BufferedReader reader = new BufferedReader(new FileReader(file))) {
            String line;
            while ((line = reader.readLine()) != null) {
                line = line.replace(" ", "");
                if (StringUtils.isBlank(line) || line.startsWith("//")) {
                    continue;
                } else if (!line.contains(":")) {
                    log.info("丢弃数据 \"" + line + "\", 因为没找到键值");
                } else if (line.endsWith(":")) {
                    throw new MyRuntimeException("缺少值  " + line);
                }
                data.put(line.split(":")[0], line.split(":")[1].replace(" ", ""));
            }
        }
    }

    public static void transferData(String txtPath, String excelPath) {
        String command = CommandUtils.buildDataTransferCommand(txtPath, excelPath);
        CommandUtils.exec(command);
    }

    public static String findExcel(File file) {
        File pFile = file.getParentFile();
        File[] files = pFile.listFiles();
        assert files != null;
        for (File f : files) {
            String path = f.getAbsolutePath();
            if ((path.endsWith(".xlsx") || path.endsWith(".xls")) && !path.contains("端") && !path.contains("~")) {
                return f.getAbsolutePath();
            }
        }
        throw new MyRuntimeException("未在data文件所在目录中找到excel文件");
    }

    public static void transferUser(String txtPath, String excelPath) {
        String command = CommandUtils.buildUserTransferCommand(txtPath, excelPath);
        CommandUtils.exec(command);
    }
}
